package com.lottery.common.util;

import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;

/**
 * 
 * @描述: Cache工具类
 *
 * @author LiBing
 * @date 2016年10月22日 下午12:15:06
 *
 */
public class EhCacheUtils {

	private static EhCacheCacheManager cacheManager = ((EhCacheCacheManager)SpringContextHolder.getBean("cacheManager"));
	
	private static final String DEFAULT_CACHE = "sysCache";

	/**
	 * 获取DEFAULT_CACHE缓存
	 * @param key
	 * @return
	 */
	public static Object get(String key) {
		return get(DEFAULT_CACHE, key);
	}
	
	/**
	 * 写入DEFAULT_CACHE缓存
	 * @param key
	 * @return
	 */
	public static void put(String key, Object value) {
		put(DEFAULT_CACHE, key, value);
	}
	
	/**
	 * 从DEFAULT_CACHE缓存中移除
	 * @param key
	 * @return
	 */
	public static void remove(String key) {
		remove(DEFAULT_CACHE, key);
	}
	
	/**
	 * 获取缓存
	 * @param cacheName
	 * @param key
	 * @return
	 */
	public static Object get(String cacheName, String key) {
		ValueWrapper vw = getCache(cacheName).get(key);
		return vw==null?"":vw.get();
	}

	/**
	 * 写入缓存
	 * @param cacheName
	 * @param key
	 * @param value
	 */
	public static void put(String cacheName, String key, Object value) {
		//Element element = new Element(key, value);
		getCache(cacheName).put(key,value);
	}

	/**
	 * 从缓存中移除
	 * @param cacheName
	 * @param key
	 */
	public static void remove(String cacheName, String key) {
		getCache(cacheName).evict(key);
	}
	
	/**
	 * 获得一个Cache，没有则创建一个。
	 * @param cacheName
	 * @return
	 */
	private static Cache getCache(String cacheName){
		Cache cache = cacheManager.getCache(cacheName);
		return cache;
	}

	public static CacheManager getCacheManager() {
		return cacheManager;
	}
	
}